import pandas as pd
import numpy as np

df = pd.read_csv('static/data/book_info_pre.csv')


def line_data():
    df_line = df[(df['publish_year_month'] >= '2023-01') & (df['publish_year_month'] <= '2023-12')].groupby(['publish_year_month'])['name'].count().reset_index()
    label = [i[0] for i in df_line.values]
    data = [i[1] for i in df_line.values]
    return {
        'label': label,
        'data': data
    }


def bar_data():
    df_bar = df.sort_values(by='comment_count', ascending=False)[['name', 'comment_count']].head(10)
    label = [i[0] for i in df_bar.values]
    data = [i[1] for i in df_bar.values]
    return {
        'label': label,
        'data': data
    }


def pie_data():
    data = [
        {
            'name': f'{i * 2}折-{(i + 1) * 2}折',
            'value': len(df[(df['price_s'] < (i + 1) * 2) & (df['price_s'] > i * 2)])
        } for i in range(0, 5)
    ]
    return {
        'data': data
    }


def radar_data():
    data = [{'name': i[0], 'value': i[1:]} for i in df[['name', 'price_n', 'price_r', 'price_s']].values.tolist()]
    radar_max = [
        {'name': '折后价', 'max': int(df['price_n'].max())},
        {'name': '原价', 'max': int(df['price_r'].max())},
        {'name': '折扣', 'max': int(df['price_s'].max())},
    ]
    return {
        'data': np.array(data).reshape(548, 10).tolist(),
        'max': radar_max,
        'legend': list(range(1, 549))
    }


def word_cloud_data():
    df_word_cloud = df.groupby('publish_house')['name'].count().reset_index().sort_values(by='name',
                                                                                          ascending=False).head(50)
    data = [{'name': i[0], 'value': i[1]} for i in df_word_cloud.values]
    return {
        'data': data
    }


def treemap_data():
    data = [
        {
            'name': i[0],
            'value': len(i[1]),
            'children': [
                {
                    'name': j, 'value': 1
                } for j in i[1]['name'].values.tolist()
            ]
        } for i in df.groupby('publish_house')]
    return {
        'data': data
    }
